package com.example.democlient;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.democlient.model.Task;
import com.example.democlient.network.SocketService;
import com.example.democlient.network.serverpackets.SM_TASK_ADDRESS_UPDATE_REQUEST;
import com.example.democlient.network.serverpackets.SM_TASK_UPDATE_REQUEST;

@SuppressLint("HandlerLeak")
public class TaskCreateActivity extends Activity implements RadioGroup.OnCheckedChangeListener,OnClickListener{
	
	private Spinner mySpinner;
	private RadioGroup radioGroup;
	private RadioButton radio1;
	private RadioButton radio2;
	private EditText editTextAreaName;
	private EditText editTextTaskTel;
	private EditText editTextRemark;
	private TextView mapLocResultText;
	private int taskFlag = 1;
	private int taskAreaId;
	private String taskAreaName;
	//private String addressName;
	private double xaxis;
	private double yaxis;
	private int locFlag = 0;
	private int locTypeFlag = 0;
	private MyApplication app;
	
	Task task = new Task();
	
	Handler mainHandler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            switch (msg.what) {  
            case 1:  
            	finish();
            break;  
            case 0:  
            	Toast.makeText(MyApplication.mDemoApp.getApplicationContext(), "操作失败.",Toast.LENGTH_LONG).show();
            break;
            default:  
            break;  
            }  
            super.handleMessage(msg);  
        }  
    };  
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_create);
        mySpinner = (Spinner) findViewById(R.id.taskArea); 
        radioGroup = (RadioGroup)this.findViewById(R.id.taskFlagGroup);
        radioGroup.setOnCheckedChangeListener(this);
        radio1 = (RadioButton)this.findViewById(R.id.taskFlag1);
        radio2 = (RadioButton)this.findViewById(R.id.taskFlag2);
        editTextAreaName = (EditText)this.findViewById(R.id.taskAddress);
        editTextTaskTel = (EditText)this.findViewById(R.id.taskTel);
        editTextRemark = (EditText)this.findViewById(R.id.remark);
        mapLocResultText = (TextView)this.findViewById(R.id.mapLocResult);
        
        app = (MyApplication)this.getApplication();
        app.addActivity(this);
        app.setHandler(this.getClass(),mainHandler);
        
        List<CItem> lst = new ArrayList<CItem>();  
        CItem item = new CItem(411001, "中山区");  
        lst.add(item);  
        item = new CItem(411002, "沙河口区");  
        lst.add(item);  
        item = new CItem(411003, "西岗区");   
        lst.add(item);  
        item = new CItem(411004, "高新区");   
        lst.add(item);  
        item = new CItem(411005, "甘井子区");   
        lst.add(item);  
        item = new CItem(411006, "开发区");   
        lst.add(item);  
        
        ArrayAdapter<CItem> myaAdapter = new ArrayAdapter<CItem>(this, android.R.layout.simple_spinner_item, lst);  
        mySpinner.setAdapter(myaAdapter);  
        mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {  
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {  
                CItem selectedItem = (CItem) mySpinner.getSelectedItem();
                TaskCreateActivity.this.taskAreaId = selectedItem.GetID();
                TaskCreateActivity.this.taskAreaName = selectedItem.GetValue();
            }  
            @Override  
            public void onNothingSelected(AdapterView<?> arg0) {  
            }  
        }); 
        final ImageButton mapLocResult = (ImageButton)this.findViewById(R.id.locBtn);
        mapLocResult.setOnClickListener( new OnClickListener(){
			@Override
			public void onClick(View v) {
			       Intent intent = new Intent();
			       intent.setClass(TaskCreateActivity.this,MapLocationActivity.class);
			       String addressName = editTextAreaName.getText().toString();
			       intent.putExtra("name", addressName);
			       intent.putExtra("districtId", TaskCreateActivity.this.taskAreaId);
			       TaskCreateActivity.this.startActivityForResult(intent, CONTEXT_RESTRICTED);
			}
        });
        final Button save = (Button)this.findViewById(R.id.save);
        final Button cancel = (Button)this.findViewById(R.id.cancel);
        save.setOnClickListener(this);
        cancel.setOnClickListener(this);

        Intent myIntent = this.getIntent();
		int position = myIntent.getIntExtra("content",-1);
		if(position!=-1){
			task = app.taskList.get(position);
			for(int i=0;i<lst.size();i++){
				CItem tempCItem = lst.get(i);
				if(tempCItem.GetValue()==task.getAreaName()){
					mySpinner.setSelection(i);
				}
			}
			if(task.getFlag() == 1){
				radio1.setChecked(true);
			}else{
				radio2.setChecked(true);
			}
			editTextAreaName.setText(task.getAddressStr());
			editTextTaskTel.setText(task.getTelephone());
			editTextRemark.setText(task.getRemark());
			if(task.getAddressId()>0){
				mapLocResultText.setText("已定位");
			}
			save.setText("修    改");
		}
    }

    @Override
	public void onStart(){
		super.onStart();
		app = (MyApplication)this.getApplication();
        app.setHandler(this.getClass(),mainHandler);
	}
    
	@Override
	public void onClick(View v) {
		if(v.getId()==R.id.save ){
			String  addressName = editTextAreaName.getText().toString();
		    String  taskTel = editTextTaskTel.getText().toString();
		    String  remark = editTextRemark.getText().toString();
//			if(task==null){
//				if(locFlag==0){
//					Toast.makeText(MyApp.mDemoApp.getApplicationContext(), "请先定位坐标.",Toast.LENGTH_LONG).show();
//					return;
//			    }
//			    if(SocketService.getInstance().sendPacket(new SM_TASK_CREATE_REQUEST(taskAreaName,taskFlag,addressId,taskAreaId,addressName,taskTel,remark,locFlag,app.account), app)){
//			    	Toast.makeText(MyApp.mDemoApp.getApplicationContext(), "消息已发送.",Toast.LENGTH_LONG).show();
//			    }
//			}else{
				task.setTelephone(taskTel);
				task.setRemark(remark);
				task.setFlag(taskFlag);
				task.setAreaName(taskAreaName);
				if(locFlag==1){
					//重新定位
				    if(task.getId()==null) task.setId(-1);
					task.setAddressStr(addressName);
					task.setAreaId(taskAreaId);
			    	task.setXaxis(xaxis);
			    	task.setYaxis(yaxis);
			    	task.setAccount(app.account);
			    	task.setLocTypeFlag(locTypeFlag);
			    	if(SocketService.getInstance().sendPacket(new SM_TASK_ADDRESS_UPDATE_REQUEST(task), app)){
//				    	Toast.makeText(MyApp.mDemoApp.getApplicationContext(), "消息已发送.",Toast.LENGTH_LONG).show();
				    }else{
//				    	Toast.makeText(MyApp.mDemoApp.getApplicationContext(), "消息发送失败.",Toast.LENGTH_LONG).show();
				    }
			    }else{
			    	if(task.getId()==null){
			    		Toast.makeText(MyApplication.mDemoApp.getApplicationContext(), "请先定位坐标.",Toast.LENGTH_LONG).show();
			    		return ;
			    	}
			    	if(SocketService.getInstance().sendPacket(new SM_TASK_UPDATE_REQUEST(task), app)){
//				    	Toast.makeText(MyApp.mDemoApp.getApplicationContext(), "消息已发送.",Toast.LENGTH_LONG).show();
				    }else{
//				    	Toast.makeText(MyApp.mDemoApp.getApplicationContext(), "消息发送失败.",Toast.LENGTH_LONG).show();
				    }
			    }
//			}
		}else if(v.getId()==R.id.cancel){
			Intent toIntent = new Intent();
	 		toIntent.setClass(TaskCreateActivity.this,TaskActivity.class);
	 		startActivity(toIntent);
		}
		
	}
	
    public void onCheckedChanged(RadioGroup group, int checkedId) {
       if (checkedId == R.id.taskFlag1){
    	   this.taskFlag = 1;
       }else
       {
    	   this.taskFlag = 2;
       }
    }

    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	  super.onActivityResult(requestCode, resultCode, data);
    	  if(data!=null)
    	  {
    		  Bundle bundle = data.getExtras();
    		  locFlag = 1;
    		  locTypeFlag = bundle.getInt("locTypeFlag");
    		  mapLocResultText.setText("已定位");
    		  xaxis = bundle.getDouble("positionx");
    		  yaxis = bundle.getDouble("positiony");
    		  //addressName = bundle.getString("addressName");
    		  //editTextAreaName.setText(addressName);
    		  if(locTypeFlag==1){
    			  //addressName = bundle.getString("addressName");
    			  //editTextAreaName.setText(addressName);
    		  }
    	  }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item){
    	super.onOptionsItemSelected(item);
    	if(item.getItemId()==R.id.menu_settings){
    		app.exit();
    	}
		return true;
    }

	public class CItem {
		private int ID;
		private String Value = "";

		public CItem() {
			ID = 0;
			Value = "";
		}

		public CItem(int _ID, String _Value) {
			ID = _ID;
			Value = _Value;
		}

		@Override
		public String toString() {
			return Value;
		}

		public int GetID() {
			return ID;
		}

		public String GetValue() {
			return Value;
		}
	}
}
